<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Web\CommentRequest;
use App\Http\Requests\Web\ReportRequest;
use App\Models\Comment;
use App\Models\Report;
use App\Models\User;
use App\Models\Write;
use Illuminate\Http\Request;

class CommentController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $all = show_comments($request->write_id);
//        return cache_show_comments($write_id);//之后做权限管理，在缓存全部的，加上
    return $this->returnArray($all);
    }



    public function lock(Comment $comment){
        $comment->is_locked = 1;
        $comment->save();
        return $this->response->noContent();
    }

    //举报
    public function report(ReportRequest $request){
        $be_reported_user_id = $request->be_reported_user_id;
        $write_id =$request->write_id;
        $comment_id = $request->comment_id;
        $user_id = auth('api')->user()->id;
        if (!Write::find($write_id)){
            return $this->response->errorBadRequest('文章不存在');
        }
        if ( !User::find($be_reported_user_id)){
            return $this->response->errorBadRequest('被举报人不存在');
        }
        if ( !Comment::find($comment_id)){
            return $this->response->errorBadRequest('评论不存在');
        }
        if ($be_reported_user_id == $user_id){
            return $this->response->errorBadRequest('为什么举报自己呢');
        }
        $inserts = $request->all();
        $inserts['user_id']=$user_id;
        Report::create($inserts);
        return $this->response->created();
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */


    public function store(CommentRequest $request,Comment $comment)
    {
        $write_id = $request->input('write_id');
        $p = $request->input('pid');
        if ($p){
            $get = Comment::where('write_id',$write_id)->where('id',$p)->get()->toArray();
        }

        if (!Write::where('id',$write_id)->get()){
            return $this->response->errorBadRequest('没有文章');
        }
        $comment->write_id=$request->input('write_id');
        if (!$request->pid && $request->pid==0){
            $comment->pid= 0;
        }else if ($get[0]['pid'] ==''){
            $comment->pid = $p;
            $comment->touser_id = $get[0]['user_id'];
        } else {
                    $comment->pid = $get[0]['pid'];
            $comment->touser_id = $get[0]['user_id'];
            }

        $comment->subs=$request->input('subs');
        $comment->user_id=auth('api')->user()->id;
        $comment->save();
//        cache_show_comments_forget();//清除缓存
        return $this->response->created();

    }

}
